package com._21cn._front.utils.wxin;

import com._21cn.framework.http.HttpCaller;
import com._21cn.framework.utils.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class Sign {
	
	public static String getToken(){
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx1a20e8bd75f95b1d&secret=fdf2d00e0a25d7e2c93b66f0d631380f";
		String response = HttpCaller.post(url).call().getString();
		String token = "";
		if( !StringUtil.isEmpty(response) ){
			JSONObject jsonObject = JSON.parseObject(response);
			token = jsonObject.getString("access_token");
		}
		return token;
	}
	
	public static String getTicket(){
		String token = getToken();
		String ticket = "";
		if( !StringUtil.isEmpty(token) ){
			String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi";
			String response = HttpCaller.post(url).call().getString();
			JSONObject jsonObject = JSON.parseObject(response);
			ticket = jsonObject.getString("ticket");
		}
		return ticket;
	}
	
    public static String sign(String timeStr, String nonceStr, String jsapiTicket, String url) {
    	
        String requestUrl = "jsapi_ticket="+ jsapiTicket + "&noncestr=" + nonceStr + "&timestamp="+ timeStr + "&url="+url;
        MessageDigest md;
        StringBuffer hexstr = new StringBuffer();
		try {
			md = MessageDigest.getInstance("SHA-1");
			md.update(requestUrl.getBytes());
	        byte[] digest = md.digest();

	        String shaHex = "";
	        
	        for (int i = 0; i < digest.length; i++) {
	          shaHex = Integer.toHexString(digest[i] & 0xFF);
	          if (shaHex.length() < 2) {
	            hexstr.append(0);
	          }
	          hexstr.append(shaHex);
	        }
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return hexstr.toString();
    }

    public static String createNonceStr() {
        return UUID.randomUUID().toString();
    }

    public static String createTimeStr() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

}
